import React, { useMemo, useState } from 'react';

import { FormItemProps } from '@/typing';
import * as Icons from '@ant-design/icons/lib/icons';
import { useDebounce } from 'ahooks';
import { Input, Modal } from 'antd';

const allIcons = Object.keys(Icons);

const IconPicker: React.FC<FormItemProps> = (props) => {
  // 定义 state 打开关闭 Modal
  const [open, setOpen] = useState(false);
  // 定义 state 暂存搜索信息
  const [_search, setSearch] = useState<string>('');

  const search = useDebounce(_search, { wait: 200 });

  const showIcons = useMemo(() => {
    return allIcons.filter(
      (iconKey) => iconKey.toLowerCase().indexOf(search.toLowerCase()) > -1,
    );
  }, [search]);

  let SelectedIcon = null;
  if (props.value as keyof typeof Icons) {
    SelectedIcon = Icons[props.value as keyof typeof Icons];
  }

  return (
    <div className={'flex items-center'}>
      <Input
        addonBefore={SelectedIcon && <SelectedIcon style={{ fontSize: 22 }} />}
        placeholder={'请选择图标'}
        value={props.value}
        onFocus={(e) => {
          e.target.blur();
          setOpen(true);
        }}
      />
      <Modal
        open={open}
        onCancel={() => setOpen(false)}
        width={800}
        footer={false}
      >
        <Input.Search onChange={(e) => setSearch(e.target.value)} />
        <div className={'flex flex-wrap'}>
          {showIcons.map((value) => {
            // If using Typescript
            const Icon = Icons[value as keyof typeof Icons];

            return (
              <div
                className={
                  'mx-2 my-3 cursor-pointer items-center flex flex-col'
                }
                key={value}
                onClick={() => {
                  props.onChange?.(value);
                  setOpen(false);
                }}
              >
                <Icon style={{ fontSize: 40 }} title={value} />
              </div>
            );
          })}
        </div>
      </Modal>
    </div>
  );
};

export default IconPicker;
